package dao.impl;

import com.alibaba.druid.util.StringUtils;
import dao.MallUserDao;
import model.po.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import utils.DruidUtils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MallUserDaoImpl implements MallUserDao {
    @Override
    public List<User> getUsers(User user) {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        String sql = "select * from `user`";
        Map<String, Object> map = getDynamicSql(user);
        String base = (String) map.get("sql");
        List<Object> params = (List<Object>) map.get("parameters");
        List<User> result = null;
        try {
            result = queryRunner.query(sql + base, new BeanListHandler<>(User.class), params.toArray());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return result;
    }

    private Map<String, Object> getDynamicSql(User user) {
        String base = " where 1 = 0";
        List<Object> params = new ArrayList<>();
        if (!StringUtils.isEmpty(user.getEmail())) {
            base += " or `email` = ?";
            params.add(user.getEmail());
        }
        if (!StringUtils.isEmpty(user.getNickname())) {
            base += " or `nickname` = ?";
            params.add(user.getNickname());
        }
        if (!StringUtils.isEmpty(user.getPhone())) {
            base += " or `phone` = ?";
            params.add(user.getPhone());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("sql", base);
        map.put("parameters", params);
        return map;
    }

    @Override
    public int signup(User user) {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        String sql = "insert into `user` values(?,?,?,?,?,?,?,?)";
        int result = 0;
        try {
            result = queryRunner.update(sql, null, user.getEmail(), user.getPwd(), user.getSalt(), user.getNickname(), user.getRecipient(), user.getAddress(), user.getPhone());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return result;
    }
}
